<?php

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //获取全部评论

        //获取文章模型
        $model = $this->pj_model($request);


        $comments = $model->comment()->with(['user'])->orderBy('created_at','desc')->get();
//        dd($comments->toArray());

        return ['code'=>0,'comments'=>$comments];

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //获得当前文章模型 包括数据内容
        $model = $this->pj_model($request);
//        dd($model->toArray());
        $data = $request->only(['content']);
//        dd($data);
        $data['user_id']= auth()->id();
//        dd($data);
        //添加成功后返回当前模型 对象
        $comment = $model->comment()->create($data);
//        返回给前台数据
//        dd($comment->with('user')->find($comment['id']));
        return ['code'=>0,'comment'=>$comment->with('user')->find($comment['id'])];

    }

    //
    public function pj_model(Request $request){
        $model = $request->model;
        $id = $request->id;
        if(!strpos($model,'-')){
            $model = 'App-Model-' . $model;
        }
        $class = str_replace('-','\\',$model);
        return $class::find($id);
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
